package com.mzd.multipledatasources3.service;

import com.mzd.multipledatasources3.bean.TeachersBean;
import com.mzd.multipledatasources3.bean.TestBean;
import com.mzd.multipledatasources3.dao.test01.TransactionDao1;
import com.mzd.multipledatasources3.dao.test02.TransactionDao2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * @author Administrator
 */
@Service
public class TransactionService1 {

    @Autowired
    private TransactionDao1 ts1;
    @Autowired
    private TransactionService2 ts2;
    @Autowired
    private TransactionDao2 td2;

    @Transactional(rollbackFor = Exception.class)
    public boolean savetestBean(TestBean t) {
        return ts1.save(t);
    }

    /**
     * 全部新增失败，达到目的，是想要的结果
     */
    @Transactional(rollbackFor = Exception.class)
    public void savetestBean2(TestBean t) {
        TeachersBean tb = new TeachersBean();
        tb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        tb.setTeacherName("王老师");
        tb.setClassId("1");
        boolean b = ts2.saveTeacher(tb);
        System.out.println("新增老师 = " + b);
        int i = 1 / 0;
        boolean save = ts1.save(t);
        System.out.println("新增学生 = " + save);
    }

    /**
     * 全部新增失败，达到目的，是想要的结果
     */
    @Transactional
    public void savetestBean3(TestBean t) {
        TeachersBean tb = new TeachersBean();
        tb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        tb.setTeacherName("王老师");
        tb.setClassId("1");
        boolean b = ts2.saveTeacher2(tb);
        System.out.println("新增老师 = " + b);
//        int i = 1 / 0; //没有这行，结果一样
        boolean save = ts1.save(t);
        System.out.println("新增学生 = " + save);
    }

    /**
     * 直接注入数据源2的dao层就不受这个事务控制了
     * 全部新增失败，达到目的，是想要的结果
     */
    @Transactional
    public void savetestBean4(TestBean t) {
        TeachersBean tb = new TeachersBean();
        tb.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        tb.setTeacherName("王老师");
        tb.setClassId("1");
        boolean b = td2.save(tb);
        System.out.println("新增老师 = " + b);
        int i = 1 / 0;
        boolean save = ts1.save(t);
        System.out.println("新增学生 = " + save);
    }

}
